// pages/autofeeder/main_page.js
var ble_master = require('../ble/ble_master.js');
var autoplant_public = require('../autoplant/autoplant_public.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    settingPageIsGetInitialData: true,

    feederDeviceName: "AUTO_FDERv",
    bleServiceUUID: autoplant_public.autoPlant_ble_value.bleServiceUUID,
    bleCharUUID: autoplant_public.autoPlant_ble_value.bleCharUUID,
    feederRunnintTime: {
      int_value: 0,
      array_value: [0, 0, 0]
    },

    feederHaltTime: {
      int_value: 0,
      array_value: [0, 0, 0]
    },
    feederRunEnableHMS: {
      int_value: 0,
      array_value: [0, 0, 0]
    },
    feederRunDisableHMS: {
      int_value: 0,
      array_value: [0, 0, 0]
    },

    feederLEDState: {
      int_value: 0,
      str_value: "Off"
    },
    feederLEDStateChangeCMD: "LED",

    feederBuzzerState : {
      int_value: 0,
      str_value: "Off"
    },
    feederBuzzerStateChangeCMD: "BUZZER",

    feederRunningState: {
      int_value: 0,
      str_value: "Halt"
    },
    feederRunningStateCMD: "STATE",

    feederNextState: {
      int_value: 0,
      array_value: [0, 0, 0]
    },

    feederUTCNow: {
      int_value: 0,
      array_value: [0, 0, 0]
    },
    feederUTCSetCMD: "UTC",

    splitChar: ":",

    feederDayHMS: {
      arrary_value: [[1,2,3], [4,5,6], [7,8,9]]
    },

    feederDayHMSNow: [12, 0, 0],

    feederRunTimeCMD: "RUNTIME",
    feederHaltTimeCMD: "HALTTIME",
    feederStartTimeCMD: "STARTTIME",
    feederEndTimeCMD: "ENDTIME",

    feederPWMValue : 0,
    feederPWMCMD: "PWM",
  },

  feederDayHMSNowChange: function (e) {
    let date = new Date()
    let hms_now = this.data.feederDayHMSNow
    hms_now[0] = date.getHours()
    hms_now[1] = date.getMinutes()
    hms_now[2] = date.getSeconds()

    this.setData({
      feederDayHMSNow: hms_now
    })
  },

  feederDayHMSInit: function () {
    var hour = []
    var minute = []
    var second = []

    for (let i = 0; i < 24; i++) {
      hour.push(i)
    }

    for (let i = 0; i < 60; i++) {
      minute.push(i)
      second.push(i)
    }

    let data = this.data.feederDayHMS

    data.arrary_value[0] = hour
    data.arrary_value[1] = minute
    data.arrary_value[2] = second

    this.setData({
      feederDayHMS: data
    })

    console.log(this.data.feederDayHMS.arrary_value)
  },

  

  ble_init: function () {
    if (ble_master.data.ble_device) {
      if (!ble_master.data.isConnected) {
        this.setData({
          mainPageBLEConnectStateColor: this.data.mainPageBLEDisonnectColor,
          mainPageBLEConnectStateString: this.data.mainPageBLEDisconnecString
        })
        ble_master.ble_connectToDevice(this.ble_connectSuccessCallback)
      } else {
        this.ble_connectSuccessCallback()
      }
    } else {
      this.ble_foundSpecialDev()
    }
  },

  ble_sendData: function (res) {
    if (ble_master.data.isConnected) {
      ble_master.ble_sendData(res)
    } else {
      console.log("ble device not connect")
    }
  },

  ble_foundSpecialDev: function() {
    ble_master.ble_onDeviceFound(this.christp_foundBluetoothDeviceCallback)
    ble_master.ble_openAdaptorandStartDiscovery()
  },

  christp_afterStopBluetoothDiscovery() {
    // this.christp_jumpToAutoPlantPage()
    console.log("device found")
    ble_master.ble_connectToDevice(this.ble_connectSuccessCallback)
  },

  ble_connectSuccessCallback: function () {
    console.log("Connect to ble device " + ble_master.data.ble_device.deviceId + " success")
    // this.setData({
    //   mainPageBLEConnectStateColor: this.data.mainPageBLEConnectColor,
    //   mainPageBLEConnectStateString: this.data.mainPageBLEConnecString
    // })
    wx.showToast({
      title: 'Connected',
    })
    if (false == ble_master.data.isNotifyOn) {
      ble_master.ble_turnOnNotify(this.data.bleServiceUUID, this.data.bleCharUUID, this.ble_turnOnNotifySuccessCallback)
    } else {
      console.log("the is notify on state is " + ble_master.data.isNotifyOn)
      this.ble_turnOnNotifySuccessCallback()
    }
  },

  ble_turnOnNotifySuccessCallback: function () {
    console.log("Trun on notify success in callback function")
    ble_master.ble_getNotifyData(this.ble_getNotifyDataCallback)

    if (this.data.settingPageIsGetInitialData == true) {
      // Get running time
      let cmd_value = this.data.feederRunTimeCMD
      this.ble_sendData(ble_master.getCharsFromString(cmd_value))
    }
  },

  ble_getNotifyDataCallback: function (res) {
    let str = ble_master.getStringFromBuffer(res)
    console.log("Get notify data: " + str)

    let split_str = str.split(this.data.splitChar)
    if (2 == split_str.length) {
      let cmd_head = split_str[0]
      // console.log("split_str[0] len is " + split_str[0].length)
      // console.log("split_str[1] len is " + split_str[1].length)
      let cmd_value = ble_master.getIntFromString(split_str[1])
      console.log(cmd_head + " " + cmd_value)
      this.ble_handleReceivedData(cmd_head, cmd_value)
    } else {
      console.log("Get wrong data")
    }
  },

  ble_handleReceivedData: function(cmd_head, cmd_value) {
    if (cmd_head == this.data.feederLEDStateChangeCMD) {
      let new_state = this.data.feederLEDState
      if(cmd_value == 1) {
        new_state.str_value = "On"
        new_state.int_value = 1
      } else {
        new_state.str_value = "Off"
        new_state.int_value = 0
      }
      this.setData({
        feederLEDState: new_state
      })

      if (this.data.settingPageIsGetInitialData == true) {
        // Get buzzer state
        let cmd_value = this.data.feederBuzzerStateChangeCMD
        this.ble_sendData(ble_master.getCharsFromString(cmd_value))
      }
    } else if (cmd_head == this.data.feederBuzzerStateChangeCMD) {
      let new_state = this.data.feederBuzzerState
      if (cmd_value == 1) {
        new_state.str_value = "On"
        new_state.int_value = 1
      } else {
        new_state.str_value = "Off"
        new_state.int_value = 0
      }
      this.setData({
        feederBuzzerState: new_state
      })

      if (this.data.settingPageIsGetInitialData == true) {
        // Get pwm value
        let cmd_value = this.data.feederPWMCMD
        this.ble_sendData(ble_master.getCharsFromString(cmd_value))

        // this.setData({
        //   settingPageIsGetInitialData: false
        // })
      }
     
    } else if (cmd_head == this.data.feederUTCSetCMD) {
      console.log("get utc")
      let utc_now = this.data.feederUTCNow
      let t_cmd_value = parseInt(cmd_value / (24 * 3600))
      cmd_value = cmd_value - (t_cmd_value * 24 * 3600)
      utc_now.int_value = cmd_value
      utc_now.array_value = ble_master.hmsInt2Arrary(cmd_value, 8)
      this.setData({
        feederUTCNow: utc_now
      })
      console.log(this.data.feederUTCNow)

      if (this.data.settingPageIsGetInitialData == true) {
        // Get led state
        console.log("Get led")
        let cmd_value = this.data.feederLEDStateChangeCMD
        this.ble_sendData(ble_master.getCharsFromString(cmd_value))
      }
    } else if (cmd_head == this.data.feederRunTimeCMD) {
      let time = this.data.feederRunnintTime
      time.int_value = cmd_value
      time.array_value = ble_master.hmsInt2Arrary(cmd_value, 0)
      this.setData({
        feederRunnintTime: time
      })

      if(this.data.settingPageIsGetInitialData == true) {
        // Get halt time
        let cmd_value = this.data.feederHaltTimeCMD
        this.ble_sendData(ble_master.getCharsFromString(cmd_value))
      }
    } else if (cmd_head == this.data.feederHaltTimeCMD) {
      let time = this.data.feederHaltTime
      time.int_value = cmd_value
      time.array_value = ble_master.hmsInt2Arrary(cmd_value, 0)
      this.setData({
        feederHaltTime: time
      })

      if (this.data.settingPageIsGetInitialData == true) {
        // Get day start time
        let cmd_value = this.data.feederStartTimeCMD
        this.ble_sendData(ble_master.getCharsFromString(cmd_value))
      }
    } else if (cmd_head == this.data.feederStartTimeCMD) {
      let time = this.data.feederRunEnableHMS
      time.int_value = cmd_value
      time.array_value = ble_master.hmsInt2Arrary(cmd_value, 8)
      this.setData({
        feederRunEnableHMS: time
      })
      if (this.data.settingPageIsGetInitialData == true) {
        // Get day sleep time
        let cmd_value = this.data.feederEndTimeCMD
        this.ble_sendData(ble_master.getCharsFromString(cmd_value))
      }
    } else if (cmd_head == this.data.feederEndTimeCMD) {
      let time = this.data.feederRunDisableHMS
      time.int_value = cmd_value
      time.array_value = ble_master.hmsInt2Arrary(cmd_value, 8)
      this.setData({
        feederRunDisableHMS: time
      })
      if (this.data.settingPageIsGetInitialData == true) {
        // // Get machine utc
        let cmd_value = this.data.feederUTCSetCMD
        this.ble_sendData(ble_master.getCharsFromString(cmd_value))
        // this.setData({
        //   settingPageIsGetInitialData : false
        // })
      }
    } else if (cmd_head == this.data.feederPWMCMD) {
      this.setData({
        feederPWMValue: cmd_value
      })

      if(this.data.settingPageIsGetInitialData == true) {
        // // Get state 
        let cmd_value = this.data.feederRunningStateCMD
        this.ble_sendData(ble_master.getCharsFromString(cmd_value))
      }
    } else if (cmd_head == this.data.feederRunningStateCMD) {
      // let state_str = 'Halt'
      // if(cmd_value == 1) {
      //   state_str = 'Running'
      // }
      let state_t = this.data.feederRunningState
      if(cmd_value == 0) {
        state_t.str_value = 'Halt'
      } else {
        state_t.str_value = 'Running'
      }
      state_t.int_value = cmd_value
      this.setData({
        feederRunningState: state_t
      })
      
      if (this.data.settingPageIsGetInitialData == true) {
        this.setData({
          settingPageIsGetInitialData: false
        })
      }
    }
  },

  // Find the device and stop discovery
  christp_foundBluetoothDeviceCallback() {
    if (ble_master.ble_getDeviceinFoundDeviceListByName(this.data.feederDeviceName)) {
      ble_master.ble_stopDiscovery(this.christp_afterStopBluetoothDiscovery)
    } 
  },

  feederLEDStateChangeButton: function(e) {
    let new_state = 0
    if (this.data.feederLEDState.int_value == 0) {
      new_state = 1
    }
    let final_cmd = e.target.id + this.data.splitChar + ble_master.getStringFromInt(new_state)
    this.ble_sendData(ble_master.getCharsFromString(final_cmd))
    console.log(final_cmd)
  },

  feederBuzzerStateChangeButton: function(e) {
    let new_state = 0
    if (this.data.feederBuzzerState.int_value == 0) {
      new_state = 1
    }
    let final_cmd = e.target.id + this.data.splitChar + ble_master.getStringFromInt(new_state)
    this.ble_sendData(ble_master.getCharsFromString(final_cmd))
    console.log(final_cmd)
  },

  feederUTCSetButton: function(e) {
    let final_cmd = e.target.id + this.data.splitChar + ble_master.getStringFromInt(Math.round(new Date() / 1000))
    // console.log(Math.round(new Date() / 1000))
    this.ble_sendData(ble_master.getCharsFromString(final_cmd))
    console.log(final_cmd)
  },

  feederDayHMSChange: function(e) {
    // console.log(this.HMSInt2Arrary(this.HMSArrary2Int(e.detail.value, 8), 8))
    let cmd = e.target.id + this.data.splitChar + ble_master.getStringFromInt(ble_master.hmsArrary2Int(e.detail.value, 8))
    console.log(cmd)
    this.ble_sendData(ble_master.getCharsFromString(cmd))
  },

  feederTimeHMSChange: function(e) {
    let cmd = e.target.id + this.data.splitChar + ble_master.getStringFromInt(ble_master.hmsArrary2Int(e.detail.value, 0))
    console.log(cmd)
    this.ble_sendData(ble_master.getCharsFromString(cmd))
  },


  feederPWMSlideChanging: function (e) {
    this.setData({
      feederPWMValue: e.detail.value
    })
  },

  feederPWMSlideChange: function (e) {
    this.setData({
      feederPWMValue: e.detail.value
    })

    let motor_cmd = this.data.feederPWMCMD +  this.data.splitChar + ble_master.getStringFromInt(e.detail.value)
    console.log(motor_cmd)
    this.ble_sendData(ble_master.getCharsFromString(motor_cmd))
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.feederDayHMSInit()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.ble_init()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})